package data_report

import (
	"context"
	"strconv"

	"gitee.com/liuxuezhan/ar-platform/rpc-client/analysisClient/rpc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginReportLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 登录报表
func NewLoginReportLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginReportLogic {
	return &LoginReportLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginReportLogic) LoginReport(req *types.LoginReportRequest) (resp types.LoginReportResponse, err error) {
	resp = types.LoginReportResponse{
		Data:     make([]types.LoginReportData, 0),
		Page:     req.Page,
		PageSize: req.PageSize,
		Total:    0,
	}

	reqq := &rpc.SearchArUserLoginAnalysisReq{
		Page:      req.Page,
		Limit:     req.PageSize,
		CreatedAt: req.StartTime,
		UserId:    req.UserId,
		Sort:      req.Sort,
		Ip:        req.Ip,
		FinishAt:  req.EndTime,
	}

	analysis, err := l.svcCtx.Analysis.SearchArUserLoginAnalysis(l.ctx, reqq)
	if err != nil {
		return resp, err
	}

	for _, v := range analysis.ArUserLoginAnalysis {
		t := types.LoginReportData{
			Date:           strconv.FormatInt(v.CreatedAt, 10),
			UserId:         v.UserId,
			ParentId1:      v.ParentId,
			ParentId2:      v.UpupParentId,
			ParentId3:      v.UpupupParentId,
			Ip:             v.Ip,
			LoginTimes:     v.LoginCount,
			LastUpdateTime: v.UpdatedAt,
		}
		resp.Data = append(resp.Data, t)
	}
	resp.Total = analysis.Total
	return
}
